#import <Foundation/Foundation.h>
#import <CoreFoundation/CoreFoundation.h>
#import <GraphicsServices/GraphicsServices.h>
#import <CoreGraphics/CoreGraphics.h>

#import <UIKit/CDStructures.h>
#import <UIKit/UIPushButton.h>
#import <UIKit/UIThreePartButton.h>
#import <UIKit/UINavigationBar.h>
#import <UIKit/UIWindow.h>
#import <UIKit/UITransitionView.h>
#import <UIKit/UIView-Hierarchy.h>
#import <UIKit/UIHardware.h>
#import <UIKit/UITable.h>
#import <UIKit/UITableCell.h>
#import <UIKit/UITableColumn.h>
#import <UIKit/UISimpleTableCell.h>
#import <UIKit/UISectionList.h>
#import "GeoLaunch.h"
#import "../Location/LocLib.h"


@implementation GeoLaunch

- (void) applicationDidFinishLaunching: (id) unused
{
	err = false;
	// location init
	cellconnect();
	// initialize the lists

    window = [[UIWindow alloc] initWithContentRect: [UIHardware
        fullScreenApplicationContentRect]];
	
	struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
	alertSheet = [ [ UIAlertSheet alloc ] 
    initWithFrame: CGRectMake(0, 240, 320, 240) ]; 
	[ alertSheet setTitle:@"Connection Failed"]; 
	[ alertSheet setBodyText: [ NSString stringWithFormat: @"This may be because you don't have an internet connection right now." ] ]; 
	[ alertSheet addButtonWithTitle:@"Dismiss" ];
//	[ alertSheet addButtonWithTitle:@"Try again" ];
	[ alertSheet setDelegate: self ];	

    mainView = [[UIView alloc] initWithFrame: rect];
	[ window setContentView: mainView ]; 
    [ window orderFront: self ]; 
    [ window makeKey: self ]; 
    [ window _setHidden: NO ]; 


	 hud = [ [ UIProgressHUD alloc ] initWithFrame: rect  ]; 
    [ hud setText: @"Locating ..." ]; 
    [ mainView addSubview: hud ]; 
    [ hud show: YES ]; 

	[NSThread detachNewThreadSelector: @selector(getGeo:) toTarget: self withObject: nil];
		NSTimer *timer = [ NSTimer scheduledTimerWithTimeInterval: 5.0 
	    target: self 
	    selector: @selector(handleTimer:) 
	    userInfo: nil 
	    repeats: NO ]; 
    [window setContentView: mainView];
}

- (void) handleTimer: (NSTimer *) timer 
{ 
	if (err){
		err = false;
		[ hud show: NO ];
		[ alertSheet presentSheetFromAboveView: mainView ];
	}	
} 



- (void)applicationWillTerminate
{

}

-(void)getGeo:(id)unused{
	GeoPoint *loc = nil;
	NSAutoreleasePool *subPool = [[NSAutoreleasePool alloc] init];
	loc  = getBestTower();
	if (loc == nil){
		// this failed
		// raise an alert and fail?
		err = true;
	}else{
		NSURL *url; 
		// Replace your url here
		url = [ [ NSURL alloc ] initWithString: [NSString stringWithFormat:@"http://mazinger.cs.yale.edu/yahoolocal/search.php?lat=%f&long=%f&r=%d",[loc latitude],[loc longitude],5]]; 
		[self openURL: url];
	//	[self setValue:[NSString stringWithFormat:@"(%f,%f)",[loc latitude],[loc longitude]] withKey:@"GeoLoc"];
	}
	[subPool release];
	return;	
}

- (void)alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button{
	NSLog(@"Terminate");
	[alertSheet dismiss];
	[self terminate];
}


@end
